package com.primeton.fickviewtest;

import java.util.List;

import com.espertech.esper.client.EventType;
import com.espertech.esper.core.context.util.AgentInstanceViewFactoryChainContext;
import com.espertech.esper.core.service.StatementContext;
import com.espertech.esper.epl.expression.ExprNode;
import com.espertech.esper.view.View;
import com.espertech.esper.view.ViewFactory;
import com.espertech.esper.view.ViewFactoryContext;
import com.espertech.esper.view.ViewFactorySupport;
import com.espertech.esper.view.ViewParameterException;

public class CountViewFactory extends ViewFactorySupport {
	private ViewFactoryContext	viewFactoryContext;

	private List<ExprNode>			viewParameters;

	private Integer							hour;

	private Integer							minute;

	@Override
	public void setViewParameters(ViewFactoryContext viewFactoryContext, List<ExprNode> viewParameters)
			throws ViewParameterException {
		// TODO Auto-generated method stub
		this.viewFactoryContext = viewFactoryContext;
		if (viewParameters.size() != 2) {
			throw new ViewParameterException("The view requires tow parameters:expression returning hour and minute value!");
		}
		this.viewParameters = viewParameters;

	}

	@Override
	public void attach(EventType parentEventType, StatementContext statementContext, ViewFactory optionalParentFactory,
			List<ViewFactory> parentViewFactories) throws ViewParameterException {
		// TODO Auto-generated method stub
		ExprNode[] nodes = ViewFactorySupport.validate("Count Current Day View", parentEventType, statementContext,
				viewParameters, true);
		ExprNode hourExpression = nodes[0];
		ExprNode minuteExpression = nodes[1];
		if (hourExpression.getExprEvaluator().getType() != Integer.class) {
			throw new ViewParameterException("View requires a Integer type value at parameter 1");
		}
		hour = Integer.parseInt(hourExpression.toExpressionString());
		if (hour < 0 || hour > 23) {
			throw new ViewParameterException("View requires a Integer type value rang 0-23 at parameter 1");
		}
		if (minuteExpression.getExprEvaluator().getType() != Integer.class) {
			throw new ViewParameterException("View requires a Integer type value at parameter 2");
		}
		minute = Integer.parseInt(minuteExpression.toExpressionString());
		if (minute < 0 || minute > 59) {
			throw new ViewParameterException("View requires a Integer type value rang 0-59 at parameter 2");
		}

	}

	@Override
	public View makeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext) {
		// TODO Auto-generated method stub
		return new CountView(agentInstanceViewFactoryContext, hour, minute);
	}

	@Override
	public EventType getEventType() {
		// TODO Auto-generated method stub
		return CountView.getEventType(viewFactoryContext.getEventAdapterService());
	}

}
